const express = require('express');
const router = express.Router();
const pool = require('../config/db');
const { verifyToken } = require('../middleware/auth');
const { formatResponse } = require('../utils/response');
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/');
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + path.extname(file.originalname));
  }
});
const upload = multer({ storage });

// 获取用户信息
router.get('/me', verifyToken, async (req, res) => {
  try {
    const [rows] = await pool.execute('SELECT id, username, email, mobile, avatar, gender, age, createdAt FROM users WHERE id = ?', [req.userId]);
    
    if (rows.length === 0) {
      return res.status(404).json(formatResponse(404, '用户不存在'));
    }
    
    res.json(formatResponse(200, '成功', rows[0]));
  } catch (error) {
    res.status(500).json(formatResponse(500, '错误', error.message));
  }
});

// 更新用户信息
router.put('/me', verifyToken, async (req, res) => {
  try {
    const { username, email, password, mobile, age, gender, avatar } = req.body;
    const userId = req.userId;
    const updates = Object.fromEntries(
      Object.entries({ username, email, mobile, age, gender, avatar }).filter(([_, v]) => v !== undefined)
    );

    // 邮箱唯一性检查
    if (email) {
      const [emailCheck] = await pool.execute('SELECT id FROM users WHERE email = ? AND id != ?', [email, userId]);
      if (emailCheck.length) return res.status(400).json(formatResponse(400, '邮箱已被注册'));
    }

    // 密码加密处理
    if (password) updates.password = await bcrypt.hash(password, await bcrypt.genSalt(10));

    if (!Object.keys(updates).length) return res.status(400).json(formatResponse(400, '没有需要更新的字段'));

    // 执行更新并返回结果
    const [updateFields, values] = [Object.keys(updates).map(k => `${k} = ?`), Object.values(updates)];
    await pool.execute(`UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`, [...values, userId]);
    const [result] = await pool.execute('SELECT id, username, email, mobile, age, gender, avatar FROM users WHERE id = ?', [userId]);
    res.json(formatResponse(200, '用户信息更新成功', result[0]));
  } catch (error) {
    console.error('更新用户信息失败:', error);
    res.status(500).json(formatResponse(500, '更新用户信息失败', error.message));
  }
});

// 上传用户头像
router.post('/avatar', verifyToken, upload.single('avatar'), async (req, res) => {
  try {
    const userId = req.userId;
    // 直接使用内存中的二进制数据
    const avatarData = req.file.data;
    
    // 更新头像为二进制数据
    await pool.execute('UPDATE users SET avatar = ? WHERE id = ?', [avatarData, userId]);
    
    res.json(formatResponse(200, '头像更新成功'));
  } catch (error) {
    res.status(500).json(formatResponse(500, '头像上传失败', error.message));
  }
});

// 修改密码
router.put('/password', verifyToken, async (req, res) => {
  try {
    const userId = req.userId;
    const { oldPassword, newPassword } = req.body;
    
    // 获取当前密码
    const [rows] = await pool.execute('SELECT password FROM users WHERE id = ?', [userId]);
    
    if (rows.length === 0) {
      return res.status(404).json(formatResponse(404, '用户不存在'));
    }
    
    const user = rows[0];
    const isPasswordValid = await bcrypt.compare(oldPassword, user.password);
    
    if (!isPasswordValid) {
      return res.status(401).json(formatResponse(401, '旧密码错误'));
    }
    
    const hashedPassword = await bcrypt.hash(newPassword, 10);
    await pool.execute('UPDATE users SET password = ? WHERE id = ?', [hashedPassword, userId]);
    
    res.json(formatResponse(200, '密码更新成功'));
  } catch (error) {
    res.status(500).json(formatResponse(500, '密码更新失败', error.message));
  }
});

// 获取用户公开信息

module.exports = router;
